package a51qindian.com.comprehensive.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.li.utils.ImageUtil;
import com.li.utils.ToastUtil;
import com.li.widget.CircleImageView;
import com.li.widget.MultipleLayout;
import com.li.widget.PersonalDetailItem;
import com.li.widget.TopNavigationBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.model.BaseModel;
import a51qindian.com.comprehensive.model.UserDetailInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import a51qindian.com.comprehensive.util.SpUtil;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Author: Li
 * Date: 2017/10/9 0009
 * Description: 个人信息界面
 */

public class PersonalDetailActivity extends QDBaseActivity {


    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.img_avatar)
    CircleImageView mImgAvatar;
    @BindView(R.id.layout_name)
    PersonalDetailItem mLayoutName;
    @BindView(R.id.layout_sex)
    PersonalDetailItem mLayoutSex;
    @BindView(R.id.layout_mobile)
    PersonalDetailItem mLayoutMobile;
    @BindView(R.id.layout_id)
    PersonalDetailItem mLayoutId;
    @BindView(R.id.layout_parent)
    PersonalDetailItem mLayoutParent;
    @BindView(R.id.layout_address)
    PersonalDetailItem mLayoutAddress;
    @BindView(R.id.layout_commission)
    PersonalDetailItem mLayoutCommission;
    @BindView(R.id.layout_zfb)
    PersonalDetailItem mLayoutZfb;
    @BindView(R.id.layout_bank)
    PersonalDetailItem mLayoutBank;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    private String mKey;


    private static final String IMG_NAME = "avatar.jpg";
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_detail;
    }

    private Uri mUri;

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        getUserInfo(SpUtil.getUserInfo(this, SpUtil.USER_ID), "android");
        generateUri();
    }

    private void generateUri() {
        File fileDir = new File(getExternalCacheDir(), "xiaosui");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File file = new File(fileDir, IMG_NAME);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (Build.VERSION.SDK_INT >= 24) {
            mUri = ImageUtil.getImageContentUri(this, file);
        } else {
            mUri = Uri.fromFile(file);
        }
    }

    /**
     * 获取用户西信息
     *
     * @param uid     用户编号
     * @param request 请求  android
     */
    private void getUserInfo(String uid, String request) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("request", request);
        ObservableHelper.createObservable(RetrofitCreator.createService().userDetailInfo(map))
                .subscribe(new SelectorObserver<BaseModel<UserDetailInfo>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        mLayoutContent.onSuccess();
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseModel<UserDetailInfo> userDetailInfoBaseModel) {
                        mLayoutContent.onSuccess();
                        UserDetailInfo detailInfo = userDetailInfoBaseModel.getData();
                        RequestOptions options = new RequestOptions();
                        options.placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher);
                        Glide.with(PersonalDetailActivity.this).load(detailInfo.getAvatar()).apply(options).into(mImgAvatar);

                        mLayoutName.setTxtRight(detailInfo.getRealname());
                        mLayoutSex.setTxtRight(detailInfo.getSex().equals("1") ? "男" : "女");
                        mLayoutMobile.setTxtRight(detailInfo.getMobile());
                        mLayoutId.setTxtRight(detailInfo.getIdcard() == null ? "" : detailInfo.getIdcard().toString());
                        mLayoutParent.setTxtRight(detailInfo.getParent());
                        mLayoutAddress.setTxtRight(detailInfo.getAddress() == null ? "" : detailInfo.getAddress().toString());

                        if (!TextUtils.isEmpty(detailInfo.getCommission())) {
                            String commission = detailInfo.getCommission() + "%";
                            mLayoutCommission.setTxtRight(commission);
                        }

                        mLayoutZfb.setTxtRight(detailInfo.getAlipay() == null ? "" : detailInfo.getAlipay().toString());
                        mLayoutBank.setTxtRight(detailInfo.getBank_card() == null ? "" : detailInfo.getBank_card().toString());

                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }
                });
    }

    /**
     * 修改个人信息
     *
     * @param uid   用户编号
     * @param key   修改的项  头像|姓名|性别|联系电话|地址|身份证|支付宝账号|银行账号|联系电话
     *              avatar|realname|sex|address|idcard|alipay|bank_card|mobile
     * @param value 值
     */
    private void updateUserInfo(String uid, String key, String value) {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put(key, value);
        ObservableHelper.createObservable(RetrofitCreator.createService().updateUserInfo(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        try {
                            JSONObject object = new JSONObject(s);
                            if (object.getInt("code") == 1) {
                                getUserInfo(mUid, "android");
                            } else {
                                showToast(object.getString("info"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @OnClick({R.id.layout_avatar, R.id.layout_name, R.id.layout_sex, R.id.layout_mobile, R.id.layout_id, R.id.layout_address, R.id.layout_zfb, R.id.layout_bank})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_avatar:
                mKey = "avatar";
                showAvatarDialog();
                break;
            case R.id.layout_sex:
                mKey = "sex";
                showSexDialog(mKey);
                break;
            case R.id.layout_name:
                mKey = "realname";
                showUpdateDialog("请输入姓名", mKey);
                break;
            case R.id.layout_mobile:
                mKey = "mobile";
                showUpdateDialog("请输入手机号", mKey);
                break;
            case R.id.layout_id:
                mKey = "idcard";
                showUpdateDialog("请输入身份证", mKey);
                break;
            case R.id.layout_address:
                mKey = "address";
                showUpdateDialog("请输入详细地址", mKey);
                break;
            case R.id.layout_zfb:
                mKey = "alipay";
                showUpdateDialog("请输入支付宝账号", mKey);
                break;
            case R.id.layout_bank:
                mKey = "bank_card";
                showUpdateDialog("请输入银行卡号", mKey);
                break;
        }
    }


    private void showUpdateDialog(String hint, final String key) {
        View updateView = getLayoutInflater().inflate(R.layout.layout_update_dialog, null);
        final EditText editText = updateView.findViewById(R.id.et_update);
        editText.setHint(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(PersonalDetailActivity.this)
                .setTitle("提示")
                .setView(updateView)
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updateUserInfo(mUid, key, editText.getText().toString());
                    }
                });
        builder.create().show();
    }

    private void showSexDialog(final String key) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("请选择性别")
                .setItems(new String[]{"男", "女"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updateUserInfo(mUid, key, String.valueOf(which + 1));
                    }
                });
        builder.create().show();
    }

    private void showAvatarDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("请选择来源")
                .setItems(new String[]{"相机", "图库"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                ImageUtil.takePicture(PersonalDetailActivity.this, CODE_CAMERA_REQUEST, mUri);
                                break;
                            case 1:

                                ImageUtil.chooseLocaleImage(PersonalDetailActivity.this, CODE_GALLERY_REQUEST);
                                break;
                        }
                    }
                });
        builder.create().show();
    }
    private Uri realUri;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CODE_GALLERY_REQUEST:
                if (resultCode == Activity.RESULT_CANCELED) {
                    return;
                }
                realUri = Uri.fromFile(new File(getExternalCacheDir(), "head.jpg"));
                ImageUtil.crop(PersonalDetailActivity.this, data.getData(), realUri, CODE_RESULT_REQUEST,
                        mImgAvatar.getWidth()*3, mImgAvatar.getHeight()*3);
                break;
            case CODE_CAMERA_REQUEST:
                if (resultCode == Activity.RESULT_CANCELED) {
                    return;
                }
                realUri = Uri.fromFile(new File(getExternalCacheDir(), "head.jpg"));
                ImageUtil.crop(this, mUri, realUri, CODE_RESULT_REQUEST,
                        mImgAvatar.getWidth()*3, mImgAvatar.getHeight()*3);
                break;
            case CODE_RESULT_REQUEST:
                if (resultCode == Activity.RESULT_CANCELED) {
                    return;
                }
                uploadFile(new File(getExternalCacheDir(), "head.jpg"));
                break;
        }

    }
    private String mPhotoId;
    /**
     * 上传图片
     *
     * @param file 图片文件
     */
    private void uploadFile(File file) {
        mLayoutContent.onLoadingWithContent("正在上传");
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("photo", file.getName(), requestFile);
        ObservableHelper.createObservable(RetrofitCreator.createService().uploadFile(body))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            ToastUtil.showToast(PersonalDetailActivity.this, object.getString("info"));
                            object = object.getJSONObject("data");
                            mPhotoId = object.getString("photo_id");
                            updateUserInfo(mUid,mKey,mPhotoId);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
